package com.example.automobile_positioning.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Thumbnails;
import android.provider.MediaStore.Video.VideoColumns;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.example.automobile_positioning.R;
import com.example.automobile_positioning.util.ImageThumbnail;

/**
 * 
 * @author liuyeping
 * 
 *         门头照
 * 
 */
public class AaaaActivity extends Activity {
	// 自定义的弹出框类
	private Button mPhoto;
	Uri imageUri=null;
	private View viewBg;
	List<Bitmap> bitmaps2 = new ArrayList<Bitmap>();
	ImageAdapter adapter;
	GridView gv;
	private Bitmap bitmap;
	private static final String FILE_PATH = Environment.getExternalStorageDirectory().getPath()+"/MyImage";
	private ImageView iv;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题
		setContentView(R.layout.activity_aaaaa);
		iv = (ImageView) findViewById(R.id.iv);

		// 把一个集合的照片显示出来
		for (Bitmap bitmap : MainActivity.bitmapsPhoto) {
			bitmap = ThumbnailUtils.extractThumbnail(bitmap, 220, 220);
			bitmaps2.add(bitmap);
		}
		mPhoto = (Button) findViewById(R.id.btn_photo);
		gv = (GridView) findViewById(R.id.gv);
		viewBg = findViewById(R.id.myView);// 初始化遮罩层
		adapter = new ImageAdapter();
		gv.setAdapter(adapter);
		// 把文字控件添加监听，点击弹出自定义窗口
		mPhoto.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showpop();
			}
		});

	}

	// Gridview的适配器
	private class ImageAdapter extends BaseAdapter {
//		List<Bitmap> bitmaps = new ArrayList<Bitmap>();

//		public ImageAdapter(List<Bitmap> bitmaps) {
//			this.bitmaps = bitmaps;
//		}

		@Override
		public int getCount() {
			return bitmaps2.size();
		}

		@Override
		public Object getItem(int arg0) {
			return bitmaps2.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public View getView(int postion, View arg1, ViewGroup arg2) {
			ImageView iv = new ImageView(AaaaActivity.this);
			iv.setImageBitmap(bitmaps2.get(postion));
			return iv;
		}

	}

	

	/**
	 * 显示Pop窗口
	 * 
	 * @param context
	 */
	
	public void showpop() {
		View view = getLayoutInflater().inflate(
				R.layout.popwindow_head_portrait, null);
		// 最后一个参数false 代表：不与其余布局发生交互， true代表：可以与其余布局发生交互事件
		final PopupWindow popWindow = new PopupWindow(view,
				LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, false) {
			// 重写popupWindow消失时事件
			@Override
			public void dismiss() {
				// 在pop消失之前，给咱们加的view设置背景渐变出场动画（Android3.0以上的开发环境，这里建议使用属性动画，那样很柔和，视觉效果更棒！）
				viewBg.startAnimation(AnimationUtils.loadAnimation(
						AaaaActivity.this,
						R.anim.anim_bookshelf_folder_editer_exit));
				viewBg.setVisibility(View.GONE);
				super.dismiss();
			}
		};
		// 设置Pop入场动画效果
		popWindow.setAnimationStyle(R.style.bottom_PopWindowAnimation);
		// 设置Pop响应内部区域焦点
		popWindow.setFocusable(true);
		// 设置Pop响应外部区域焦点
		popWindow.setOutsideTouchable(true);
		// 设置PopupWindow弹出软键盘模式（此处为覆盖式）
		popWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
		popWindow
				.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
		// 响应返回键必须的语句
		popWindow.setBackgroundDrawable(new BitmapDrawable());
		// 在显示pop之前，给咱们加的view设置背景渐变入场动画（Android3.0以上的开发环境，这里建议使用属性动画，那样很柔和，视觉效果更棒！）
		viewBg.setVisibility(View.VISIBLE);
		viewBg.startAnimation(AnimationUtils.loadAnimation(this,
				R.anim.anim_bookshelf_folder_editer_enter));
		// 依附的父布局自己设定，我这里为了方便，这样写的。
		popWindow.showAtLocation(viewBg, Gravity.BOTTOM, 0, 0);
		// popWindow内的控件点击监听
		OnClickListener clickListener = new OnClickListener() {
			@Override
			public void onClick(View v) {
				switch (v.getId()) {
				case R.id.popwindow_head_portrait_paizhao:
					// 根据文件地址创建文件
		             File filePic = new File(FILE_PATH);
		             if (filePic.exists()) {
		            	 filePic.delete();
		             }
		             
		            Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					  imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"workupload.jpg"));  
					//指定照片保存路径（SD卡），workupload.jpg为一个临时文件，每次拍照后这个图片都会被替换  
					cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
					startActivityForResult(cameraIntent, 1);  
					break;
				case R.id.popwindow_head_portrait_luxiang:
//					Intent intent = new Intent();
//					intent.setAction("android.media.action.VIDEO_CAPTURE");
//					intent.addCategory("android.intent.category.DEFAULT");
//					File file = new File(FILE_PATH);
//					if (file.exists()) {
//						file.delete();
//					}
//					File files = new File(file + "/video_"
//							+ System.currentTimeMillis() + ".3gp");
//					Uri uri = Uri.fromFile(files);
//					// 限制时长
//					intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
//					startActivityForResult(intent, 0);
					
		            Intent intent = new Intent();
		             intent.setAction("android.media.action.VIDEO_CAPTURE");
		             intent.addCategory("android.intent.category.DEFAULT");
		          // 根据文件地址创建文件
		             File filepath = new File(FILE_PATH);
						if (filepath.exists()) {
							filepath.delete();
						}
		             File files = new File(filepath + "/video_"+ System.currentTimeMillis() + ".3gp");
					 Uri uri = Uri.fromFile(files);
	                 intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
	                 intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
//	                 intent.putExtra(MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED);
		             startActivityForResult(intent, 0);
					Toast.makeText(AaaaActivity.this, "录像。。", 0).show();
					break;
				}
				popWindow.dismiss();
			}
		};
		view.findViewById(R.id.popwindow_head_portrait_back)
				.setOnClickListener(clickListener);
		view.findViewById(R.id.popwindow_head_portrait_paizhao)
				.setOnClickListener(clickListener);
		view.findViewById(R.id.popwindow_head_portrait_luxiang)
				.setOnClickListener(clickListener);
	}	
	
	
	

	// 保存在SD卡
	public void gridviews() {
		String sdStatus = Environment.getExternalStorageState();
		if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
			Log.v("TestFile", "SD card is not avaiable/writeable right now.");
			return;
		}
		FileOutputStream b = null;
		File file = new File(FILE_PATH);
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");// 获取当前时间，进一步转化为字符串
		String fileName = file +"/img_"+System.currentTimeMillis()+ ".jpg";
		if (!file.exists()) {
			file.mkdirs();// 创建文件夹
		}
		try {
			if (bitmap == null) {
				Toast.makeText(this, "图片格式错误，请重新添加图片", 0).show();

			} else {
				b = new FileOutputStream(fileName);
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				if (b == null || bitmap == null) {
				} else {
					b.flush();
					b.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (bitmap != null) {
			bitmap = ThumbnailUtils.extractThumbnail(bitmap, 220, 220);// 设置图片的缩略图
			bitmaps2.add(bitmap);
			Log.i("jinchim", "" + bitmaps2.size());
//			gv.setVerticalSpacing(10);// 设置GridView的间距
			adapter.notifyDataSetChanged();
		}
	}

	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (requestCode == 0) {
			//捕捉的图像 保存到Intent指定的fileUri
			Uri uri = data.getData();
			Cursor cursor = this.getContentResolver().query(uri, null, null,
			null, null);
			if (cursor != null && cursor.moveToNext()) {
			int id = cursor.getInt(cursor.getColumnIndex(VideoColumns._ID));
			String filePath = cursor.getString(cursor.getColumnIndex(VideoColumns.DATA));
			Bitmap bitmap = Thumbnails.getThumbnail(getContentResolver(),
			id, Thumbnails.MICRO_KIND, null);
			//ThumbnailUtils类2.2以上可用
			// Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(filePath, Thumbnails.MICRO_KIND);
			iv.setImageBitmap(bitmap);
			cursor.close();
			MainActivity.bitmapsPhoto.add(bitmap);
			gridviews();
		}
	}
		else if (resultCode == Activity.RESULT_OK) {
			 Bitmap camorabitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+"/workupload.jpg"); 
			 if(null != camorabitmap ){
		         // 下面这两句是对图片按照一定的比例缩放，这样就可以完美地显示出来。
		         int scale = ImageThumbnail.reckonThumbnail(camorabitmap.getWidth(),camorabitmap.getHeight(), 500, 600);   
		         bitmap = ImageThumbnail.PicZoom(camorabitmap, camorabitmap.getWidth() / scale,camorabitmap.getHeight() / scale);  
		         //由于Bitmap内存占用较大，这里需要回收内存，否则会报out of memory异常  
		         camorabitmap.recycle();  
		        //将处理过的图片显示在界面上   
		         MainActivity.bitmapsPhoto.add(bitmap);
		         gridviews();   
		         new File(Environment.getExternalStorageDirectory()+"/workupload.jpg").delete(); // 删除临时保存图片
		       }
		
		}
		super.onActivityResult(requestCode, resultCode, data);
	}


}